package com.school.movie.common.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.ss.formula.functions.T;

import java.lang.reflect.Field;
import java.util.List;


/**
 * @author sk
 * @version 1.0
 * @date 2019-12-16
 */
@Slf4j
public class BeanUtils extends org.springframework.beans.BeanUtils {

    /**
     * @param src         待比较对象
     * @param target      待比较对象
     * @param excludeName 需要排除比较的属性 可变参(可传可不传)
     * @return true:表示两个实体的所有属性值相同 false: 表示属性的值不相同
     */
    public static boolean compareTwoBean(Object src, Object target, String... excludeName) {
        Class<?> clazz1 = src.getClass();
        Class<?> clazz2 = target.getClass();
        Field[] field1 = clazz1.getDeclaredFields();
        Field[] field2 = clazz2.getDeclaredFields();
        a:
        for (int i = 0; i < field1.length; i++) {
            b:
            for (int j = 0; j < field2.length; j++) {
                if (field1[i].getName().equals(field2[j].getName()) && !ArrayUtils.contains(excludeName.clone(), field1[i].getName())) {
                    field1[i].setAccessible(true);
                    field2[j].setAccessible(true);
                    try {
                        return compareTwoValue(field1[i].get(src), field2[j].get(target));
                    } catch (IllegalAccessException e) {
                        log.error("Property value gets the exceptio ! Cache not updated", e);
                        return true;
                    }
                }
            }
        }
        return true;
    }

    /**
     * @param object1 待比较的对象中的相同的属性值
     * @param object2 待比较的对象中的相同的属性值
     * @return
     */
    public static boolean compareTwoValue(Object object1, Object object2) {

        if (object1 == null && object2 == null) {
            return true;
        }
        if (object1 == null && object2 != null) {
            return false;
        }
        if (object1.equals(object2)) {
            return true;
        }
        if (object1 == object2) {
            return true;
        }
        return false;
    }

    public static <T> T sourceToObj(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(source), target);
    }

    public static List<T> sourceToArray(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        return JSON.parseArray(JSON.toJSONString(source), target);
    }

}
